from fastapi import APIRouter, HTTPException

from api.msg.form import MsgCreateForm, MsgDeleteForm
from api.msg.models import Message
from api.msg.serializer import MsgCreateSerializer, MsgListSerializer

msg = APIRouter(prefix="/msg", tags=["msg接口路由"])


@msg.get("/index")
async def get_msg():
    messages = await Message.all()
    # result = {"msgs": messages}
    return messages


@msg.post("/create", response_model=MsgCreateSerializer)
async def create_msg(message_in: MsgCreateForm):
    message = Message(content=message_in.content, kind=message_in.kind, addr=message_in.addr)
    await message.save()
    return message


@msg.patch("/update/{msg_id}", response_model=MsgCreateSerializer)
async def create_msg(msg_id: int, message_in: MsgCreateForm):
    message = await Message.get_or_none(id=msg_id)
    if not message:
        raise HTTPException(status_code=404, detail=f"Msg {msg_id} not found")
    await message.update_from_dict(message_in.dict())
    await message.save()
    return message


@msg.patch("/update")
async def create_msg(message_in1: MsgCreateForm, message_in2: MsgCreateForm):
    flag = False
    message = None
    for key, val in message_in1.dict(exclude_unset=True).items():
        if not flag:
            flag = True
            message = Message.all()
        message = message.filter(**{key: val})
    if message:
        await message.update(**message_in2.dict(exclude_unset=True))
    return {"success": "更新成功"}


@msg.delete("/delete/{msg_id}")
async def create_msg(msg_id: int):
    message = await Message.get_or_none(id=msg_id)
    if message:
        await message.delete()
    return {"success": "删除成功"}


@msg.delete("/delete")
async def create_msg(message_in: MsgDeleteForm):
    message = Message.all()
    for key, val in message_in.dict().items():
        if val is not None:
            message = message.filter(**{key: val})
    if message:
        await message.delete()
    return {"success": "删除成功"}
